import { isBlank, isArray, isObject, isNumber } from '@web-utils/core'

export const getExtension = (businessObject, type) => {
  if (!businessObject?.extensionElements) {
    return null
  }
  return businessObject.extensionElements.get('values').filter(e => e.$instanceOf(type))[0]
}

export const getExtensionByElement = (element, type) => {
  const { businessObject } = element
  return getExtension(businessObject, type)
}
export const getElementProp = (element, prop = 'body') => {
  if (element) {
    return element.get(prop)
  }
  return null
}

export const getExtensionProp = (businessObject, type, prop = 'body') => {
  return getElementProp(getExtension(businessObject, type), prop)
}

export const getExtensionPropByElement = (element, type, prop = 'body') => {
  return getElementProp(getExtensionByElement(element, type), prop)
}

export const updateExtensionProps = ({ moddle, modeling }, element, type, attrs) => {
  const { businessObject } = element
  let { extensionElements } = businessObject

  if (!extensionElements) {
    extensionElements = moddle.create('bpmn:ExtensionElements')
    businessObject.extensionElements = extensionElements
  }
  let target = getExtension(businessObject, type)
  if (!target) {
    target = moddle.create(type, attrs)
    extensionElements.get('values').push(target)
  } else {
    for (const attrsKey in attrs) {
      target.set(attrsKey, attrs[attrsKey])
    }
  }
}

export const removeExtensionElement = ({ modeling }, element, type) => {
  const { businessObject } = element
  const { extensionElements } = businessObject

  if (extensionElements) {
    const elements = extensionElements.get('values').filter(e => !e.$instanceOf(type))
    extensionElements.set('values', elements)
    modeling.updateProperties(element, { extensionElements })
  }
}

export const updateExtensionProp = (bpmnInstances, element, type, value, prop = 'body') => {
  if (isBlank(value)) {
    removeExtensionElement(bpmnInstances, element, type)
  } else {
    let str = value
    if (isArray(value) || isObject(value)) {
      str = JSON.stringify(value)
    } else if (isNumber(value)) {
      str = `${value}`
    }
    updateExtensionProps(bpmnInstances, element, type, { [prop]: str })
  }
}

export const updateProp = (bpmnInstances, element, prop = 'body', value) => {
  updateProps(bpmnInstances, element, { [prop]: value })
}

export const updateProps = ({ modeling }, element, props) => {
  modeling.updateProperties(element, props)
}

export const toTrue = value => ['true', 'Y', true, 'YES', 'yes', 'Yes'].includes(value)
